package com.zhuiyun.pm.client.login.utils;

import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.ibatis.javassist.scopedpool.ScopedClassPoolFactory;
import com.auth0.jwt.JWT;
import java.util.UUID;

import java.util.Date;

/**
 * @ClassName TokenUtils
 * @Description TODO :Token生成util
 * @Author sgo
 * @Date 2023/3/16 14:11
 **/
public class TokenUtils {

    //创建token
    public String createToken(String userUuid) {
        try {
            //设置密钥及算法 a
            Algorithm algorithm = Algorithm.HMAC256("Yss321SSy");
            //生成token
            String token = JWT.create().//b
                    withExpiresAt(DateUtils.addDays(new Date(), 7)).//c
                    withClaim("uid", userUuid).//d
                    withClaim("createTime", new Date()).
                    sign(algorithm);//e
            return token;
        } catch (Exception exception) {
            throw new RuntimeException("token生成失败");
        }
    }
    //使用签名验证
    public String checkToken(String token) {
        if (StringUtils.isBlank(token)) {
            return "token is blank";
        }
        DecodedJWT jwt = null;
        try {
            //设置密钥及算法
            Algorithm algorithm = Algorithm.HMAC256("Yss321SSy");
            JWTVerifier verifier = JWT.require(algorithm).build();//f
            jwt = verifier.verify(token);//g
            String uid = jwt.getClaims().get("uid").asString();//h
            Date date = jwt.getClaims().get("createTime").asDate();
            System.out.println("date:" + date);
            return uid;
        } catch (Exception e) {
            return "checkToken error";
        }
    }
    //不使用签名验证
    public DecodedJWT decode(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        try {
            DecodedJWT decodedJWT = JWT.decode(token);//i
            return decodedJWT;
        } catch (Exception e) {
            return null;
        }
    }
    public static void main(String[] args) {
        TokenUtils tokenUtil = new TokenUtils();
        String uid = "15233968723";
        System.out.println("uid:" + uid);
        String result = tokenUtil.createToken(uid);
        System.out.println("生成的token：" + result);
        String uidOut = tokenUtil.checkToken(result);
        System.out.println("解密token后的uid：" + uidOut);
        DecodedJWT decodedJWT = tokenUtil.decode(result);
        System.out.println("Header:" + decodedJWT.getHeader());
        System.out.println("Payload:" + decodedJWT.getPayload());
        System.out.println("Signature:" + decodedJWT.getSignature());
        System.out.println("Token:" + decodedJWT.getToken());

    }

}
